import { AuthenticationService, RouteMapManager } from 'my-web-core/services';
import { createRouter, createWebHashHistory } from 'vue-router';

import authenticationRouter from './features/authentication/authentication-router';
import homeRouter from './features/home/home-router';
import userRouter from './features/user/user-router';
import MessageService from './shared/services/message-service';
import RouteMapConfig from './shared/services/route-map-config';

// Uses createWebHashHistory to make router work correctly when we are using mainWindow.loadFile().
const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    ...authenticationRouter,
    ...homeRouter,
    ...userRouter,
    {
      path: '/',
      component: () => import('./App.vue'),
    },
    {
      path: '',
      redirect: '/home',
    },
    {
      path: '/:pathMatch(.*)*',
      component: () => import('./shared/components/NotFound.vue'),
    },
  ],
});

router.beforeEach((to) => {
  if (AuthenticationService.isAuthenticated && to.path.toLocaleLowerCase().endsWith('login')) {
    // If user has logged in then no need to login page.
    return '/home';
  } else if (
    !RouteMapManager.checkCanActivateRoute(
      RouteMapConfig.getMapping(),
      to.path,
      AuthenticationService.currentUser,
    )
  ) {
    if (AuthenticationService.isAuthenticated) {
      // Shows message if user already logged in.
      MessageService.showWarning(
        '对不起，您当前账号没有权限使用该功能，您可以尝试以其它账号重新登录。',
      );
      return false;
    } else {
      // Redirects to login.
      return `/authentication/login?redirectTo=${to.fullPath}`;
    }
  }

  return true;
});

export default router;
